import ChargeIcon from '@/assets/img/ico_charge.png';
import DischargeIcon from '@/assets/img/ico_discharge.png';
import FailureIcon from '@/assets/img/ico_failure.png';
import SOCIcon from '@/assets/img/ico_soc.png';
import Card from '@/components/Card';
import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import Empty from '@/components/Empty';
import {
  batteryControllerGetBatteryBoxDetail,
  batteryControllerGetBatteryBoxs,
  batteryControllerGetBmsRealTimeData,
  batteryControllerGetBmuRealTimeDatas,
  batteryControllerGetBmuUnitRealTimeDatas,
} from '@/services/ess/deviceBattery';
import { Flex, Select, Space, Spin, Table, TableProps } from 'antd';
import cls from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import ColorMap from './ColorMap';
import Styles from './RealtimeMonitor.less';

//www.hncloud.com/activity/activity_2024spring.html/?p=jb51
import { useModel } from '@umijs/max';
import { useLocation } from 'react-router-dom';

const RealtimeMonitor: React.FC = () => {
  let realTimeInterval: any = null;
  // 加载效果区域
  const [boxLoading, setBoxLoading] = useState<boolean>(false);
  const [clusterLoading, setClusterLoading] = useState<boolean>(false);
  const [moduleLoading, setModuleLoading] = useState<boolean>(false);
  const [unitLoading, setUnitLoading] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  // 最高/最低温度列表
  const [highestTempObj, setHighestTempObj] = useState([
    {
      temp: '',
      name: '',
      code: '',
    },
  ]);
  const [lowestTempObj, setLowestTempObj] = useState([
    {
      temp: '',
      name: '',
      code: '',
    },
  ]);
  const highestTempTableColumns: TableProps<any>['columns'] = [
    {
      title: '最高温度',
      dataIndex: 'temp',
      width: 80,
      render: (value, record) => {
        return <span>{record?.temp ? record?.temp?.toFixed(2) : '-'}</span>;
      },
    },
    {
      title: '模组名称',
      dataIndex: 'name',
    },
    {
      title: '位置/序号',
      dataIndex: 'code',
    },
  ];
  const lowestTempTableColumns: TableProps<any>['columns'] = [
    {
      title: '最低温度',
      dataIndex: 'temp',
      width: 80,
      render: (value, record) => {
        return <span>{record?.temp ? record?.temp?.toFixed(2) : '-'}</span>;
      },
    },
    {
      title: '模组名称',
      dataIndex: 'name',
    },
    {
      title: '位置/序号',
      dataIndex: 'code',
    },
  ];
  // 最高/最低电压列表
  const [highestVolObj, setHighestVolObj] = useState([
    {
      voltage: '',
      name: '',
      code: '',
    },
  ]);
  const [lowestVolObj, setLowestVolObj] = useState([
    {
      voltage: '',
      name: '',
      code: '',
    },
  ]);
  const highestVolTableColumns: TableProps<any>['columns'] = [
    {
      title: '最高电压',
      dataIndex: 'voltage',
      width: 80,
      render: (value, record) => {
        return <span>{record?.voltage ? record?.voltage?.toFixed(2) : '-'}</span>;
      },
    },
    {
      title: '模组名称',
      dataIndex: 'name',
    },
    {
      title: '位置/序号',
      dataIndex: 'code',
    },
  ];
  const lowestVolTableColumns: TableProps<any>['columns'] = [
    {
      title: '最低电压',
      dataIndex: 'voltage',
      width: 80,
      render: (value, record) => {
        return <span>{record?.voltage ? record?.voltage?.toFixed(2) : '-'}</span>;
      },
    },
    {
      title: '模组名称',
      dataIndex: 'name',
    },
    {
      title: '位置/序号',
      dataIndex: 'code',
    },
  ];
  const [stackName, setStackName] = useState('');
  // 获取选中的模组
  const [selectedCluster, setSelectedCluster] = useState('');
  const currentClusterRef = useRef(null);
  const [clusterArray, setClusterArray] = useState([]);
  console.log('clusterArray', clusterArray);
  const clusterArrayRef = useRef(null);
  // 获取选中的堆
  const [selectedStack, setSelectedStack] = useState('');
  console.log('selectedStack', selectedStack);
  const selectedStackRef = useRef(null) as any;
  const currentStackRef = useRef(null);
  // 选中模组名称
  const [moduleName, setModuleName] = useState('');
  const [selectedModule, setSelectedModule] = useState('');
  const currentModuleRef = useRef(null);
  // 获取堆数组
  // 选中模组故障数量
  const [moduleFaultCount, setModuleFaultCount] = useState('');
  // 选中箱名称
  const [boxName, setBoxName] = useState('');
  const [boxState, setBoxState] = useState('');
  const [boxColor, setBoxColor] = useState('');
  const [selectedBox, setSelectedBox] = useState('');
  const currentBoxRef = useRef(null);
  // 簇故障数量
  const [breakNum, setBreakNum] = useState(0);
  const switchInfoArray = [
    {
      label: '温度示意图',
      value: 'temp',
    },
    {
      label: '电压示意图',
      value: 'voltage',
    },
  ];
  const switchTempArray = [
    {
      label: '实时平均温度示意图',
      value: 'realtimeTemp',
    },
    {
      label: '实时温差图',
      value: 'realtimeTempGap',
    },
  ];
  const switchVolArray = [
    {
      label: '实时电压图',
      value: 'realtimeVol',
    },
    {
      label: '实时压差图',
      value: 'realtimeVolGap',
    },
  ];
  const boxStatusMap: Map<number | null, string> = new Map([
    [1, '充电'],
    [2, '放电'],
    [0, '静置'],
    [null, '离线'],
  ]);
  const boxColorMap: Map<number | null, string> = new Map([
    [1, '#56D433'],
    [2, '#196CFE'],
    [0, '#FF8080'],
    [null, '#888'],
  ]);

  const [boxArray, setBoxArray] = useState<API.BatteryBox[]>([]);
  const [boxInfo, setBoxInfo] = useState<API.BoxRealTimeData>();
  const [dischargeOptions, setDischargeOptions] = useState<MyChartOption>();
  const [stackArray, setStackArray] = useState<API.BmsRealTimeData[]>([]);
  const stackArrayRef = useRef(null);
  // 模组列表
  const [moduleArray, setModuleArray] = useState<API.BmuRealTimeData[]>([]);
  // 单元列表
  const [unitArray, setUnitArray] = useState<API.BmuUnitRealTimeData[]>([]);
  const [unitArrayInit, setUnitArrayInit] = useState([]);
  const [unitCount, setUnitCount] = useState({
    tempCount: 0,
    voltCount: 0,
  });
  // 箱图类型
  const [boxInfoType, setBoxInfoType] = useState<string>('temp');
  const [boxArrayType, setBoxArrayType] = useState<string>('realtimeTemp');
  const [boxInfoArray, setBoxInfoArray] = useState(switchTempArray);
  // 簇图类型
  const [clusterInfoType, setClusterInfoType] = useState<string>('temp');
  const [clusterArrayType, setClusterArrayType] = useState<string>('realtimeTemp');
  const [clusterInfoArray, setClusterInfoArray] = useState(switchTempArray);
  // 单元图类型
  const [unitInfoType, setUnitInfoType] = useState<string>('temp');
  /**
   * 获得放电量统计表
   * @param options
   */
  const getDischargeOptions = (options: API.NameValue[]): MyChartOption => {
    const xAxis = options.map((item) => {
      return item.name.match(/簇(\d+)/)[0];
    });
    const seriesData = options.map((item) => {
      return item.val;
    });
    return {
      grid: {
        left: 60,
        right: 3,
        bottom: 30,
      },
      xAxis: {
        axisTick: {
          alignWithLabel: true,
        },
        type: 'category',
        data: xAxis,
      },
      tooltip: {
        show: true,
        formatter: function (params) {
          return `${options[params.dataIndex].name}<br/>放电量${params.value}`;
        },
      },
      yAxis: {
        type: 'value',
        name: 'MWh',
      },
      series: [
        {
          type: 'bar',
          data: seriesData,
          itemStyle: {
            color: '#1A6CFE',
            borderColor: '#fff',
          },
        },
      ],
    };
  };
  /**
   * 获得模组下面所有的单元
   * @param module
   */
  const handleSelectModule = (module: API.BmuRealTimeData) => {
    setModuleName(module.name);
    setSelectedModule(module.code);
    currentModuleRef.current = module;
    setModuleFaultCount(module.faultCount);
    setUnitLoading(true);
    batteryControllerGetBmuUnitRealTimeDatas({
      stationId: initialState?.stationId,
      bmuCode: module.code,
    })
      .then((res) => {
        if (res.data) {
          setUnitArrayInit(res?.data?.cells || []);
          setUnitArray(res?.data?.cells.slice(0, res?.data?.tempCount) || []);
          setUnitCount({
            tempCount: res?.data?.tempCount || 0,
            voltCount: res?.data?.voltCount || 0,
          });
          setUnitLoading(false);
        } else {
          setUnitArray([]);
          setModuleName('');
          setModuleFaultCount('');
          setUnitLoading(false);
        }
      })
      .catch(() => {
        setUnitArray([]);
        setModuleName('');
        setModuleFaultCount('');
        setUnitLoading(false);
      });
  };

  function findParentStack(code: string) {
    let parentNode = null;
    (stackArrayRef?.current || []).forEach((parent) => {
      parent.clusterList.forEach((cluster) => {
        if (cluster.code === code) {
          parentNode = parent;
        }
      });
    });
    return parentNode;
  }

  /**
   * 获得簇下面的所有模组
   * @param stack
   */
  const handleSelectStack = (stack: API.ClusterRealTimeData) => {
    setStackName(stack?.name);
    setSelectedCluster(stack?.code);
    setSelectedStack(findParentStack(stack?.code)?.code);
    setClusterArray(findParentStack(stack?.code)?.clusterList);
    clusterArrayRef.current = findParentStack(stack?.code)?.clusterList;
    currentClusterRef.current = stack;
    setBreakNum(stack?.faultCount);
    setModuleLoading(true);
    if (stack && stack.code) {
      batteryControllerGetBmuRealTimeDatas({
        stationId: initialState?.stationId,
        clusterCode: stack?.code,
      })
        .then((res) => {
          // 获取最高/最低温度
          const maxTemp = res.data.reduce(
            (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
              return currentObj?.temp > maxObj?.temp ? currentObj : maxObj;
            },
          );
          setHighestTempObj([maxTemp]);
          const minTemp = res.data.reduce(
            (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
              return currentObj?.temp < maxObj?.temp ? currentObj : maxObj;
            },
          );
          setLowestTempObj([minTemp]);
          // 获取最高/最低电压
          const maxVol = res.data.reduce(
            (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
              return currentObj?.voltage > maxObj?.voltage ? currentObj : maxObj;
            },
          );
          setHighestVolObj([maxVol]);
          const minVol = res.data.reduce(
            (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
              return currentObj?.voltage < maxObj?.voltage ? currentObj : maxObj;
            },
          );
          setLowestVolObj([minVol]);
          setModuleArray(res.data);
          setModuleLoading(false);
          handleSelectModule(res.data[0]);
        })
        .catch(() => {
          setModuleLoading(false);
        });
    } else {
      setStackName('');
      setBreakNum(0);
      setHighestTempObj([]);
      setLowestTempObj([]);
      setHighestVolObj([]);
      setLowestVolObj([]);
      setModuleArray([]);
      setUnitArray([]);
      setModuleFaultCount('');
      setModuleName('');
      setModuleLoading(false);
    }
  };
  /**
   * 选择堆
   * @param stack
   */
  const handleSelectedStack = (stack: API.BmsRealTimeData) => {
    console.log('stack', stack);
    setSelectedStack(stack.code);
    currentStackRef.current = stack;
    selectedStackRef.current = stack.code;
    // setClusterArray(stack.clusterList);
    clusterArrayRef.current = stack.clusterList;
    setSelectedCluster(stack.clusterList[0]?.code);
    currentClusterRef.current = stack.clusterList[0];
  };
  /**
   * 获得箱下面所有的模组
   * @param box
   */
  const handleSelectBox = (box: API.BatteryBox) => {
    setBoxName(box?.name);
    setSelectedBox(box?.code);
    currentBoxRef.current = box;
    setBoxState(box.online ? boxStatusMap.get(box.workState) : '离线');
    setBoxColor(boxColorMap.get(box?.workState));
    if (box.code) {
      batteryControllerGetBatteryBoxDetail({
        stationId: initialState?.stationId,
        boxCode: box?.code,
      }).then((res) => {
        setBoxInfo(res.data);
        setDischargeOptions(getDischargeOptions(res.data?.clusterList));
        batteryControllerGetBmsRealTimeData({
          stationId: initialState?.stationId,
          boxCode: box?.code,
        }).then((clusterRes) => {
          if (clusterRes.data && clusterRes.data.length > 0) {
            clusterArrayRef.current = clusterRes.data[0]?.clusterList;
            setStackArray(clusterRes.data);
            stackArrayRef.current = clusterRes.data;
            setSelectedCluster(
              clusterRes.data[0]?.clusterList ? clusterRes.data[0]?.clusterList[0]?.code : '',
            );
            currentClusterRef.current = clusterRes.data[0]?.clusterList
              ? clusterRes.data[0]?.clusterList[0]
              : '';
            setClusterArray(clusterRes.data[0]?.clusterList);
            setSelectedStack(clusterRes.data[0]?.code);
            selectedStackRef.current = clusterRes.data[0]?.code;
            currentStackRef.current = clusterRes.data[0];
            handleSelectStack(
              clusterRes.data[0]?.clusterList ? clusterRes.data[0]?.clusterList[0] : [],
            );
          } else {
            setStackName('');
            setBreakNum(0);
            setStackArray([]);
            stackArrayRef.current = [];
            setModuleName('');
            setModuleFaultCount('');
            setModuleArray([]);
            setUnitArray([]);
            setHighestTempObj([]);
            setLowestTempObj([]);
            setHighestVolObj([]);
            setLowestVolObj([]);
          }
        });
      });
    }
  };
  /**
   * 定时事件
   */
  const setTimeEvent = () => {
    realTimeInterval = setInterval(() => {
      batteryControllerGetBatteryBoxs({ stationId: initialState?.stationId }).then((res) => {
        if (res.data && res.data.length > 0) {
          const box = currentBoxRef.current;
          const stack = currentStackRef.current;
          const module = currentModuleRef.current;
          const cluster = currentClusterRef.current;
          setBoxArray(res.data);
          setBoxName(box?.name);
          setSelectedBox(box?.code);
          setBoxState(
            box.workState ? boxStatusMap.get(box.workState) : box.online ? '在线' : '离线',
          );
          setBoxColor(boxColorMap.get(box?.workState));
          setClusterArray(stack.clusterList);
          clusterArrayRef.current = stack.clusterList;
          if (box?.code) {
            batteryControllerGetBatteryBoxDetail({
              stationId: initialState?.stationId,
              boxCode: box?.code,
            }).then((boxRes) => {
              setBoxInfo(boxRes.data);
              setDischargeOptions(getDischargeOptions(boxRes.data?.clusterList));
              batteryControllerGetBmsRealTimeData({
                stationId: initialState?.stationId,
                boxCode: box?.code,
              }).then((clusterRes) => {
                if (clusterRes.data && clusterRes.data.length > 0) {
                  setStackArray(clusterRes.data);
                  stackArrayRef.current = clusterRes.data;
                  setSelectedStack(clusterRes.data[0].code);
                  selectedStackRef.current = clusterRes.data[0].code;
                  setStackName(cluster?.name);
                  if (cluster && cluster.code) {
                    batteryControllerGetBmuRealTimeDatas({
                      stationId: initialState?.stationId,
                      clusterCode: cluster?.code,
                    })
                      .then((moduleRes) => {
                        // 获取最高/最低温度
                        const maxTemp = moduleRes.data.reduce(
                          (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
                            return currentObj?.temp > maxObj?.temp ? currentObj : maxObj;
                          },
                        );
                        setHighestTempObj([maxTemp]);
                        const minTemp = moduleRes.data.reduce(
                          (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
                            return currentObj?.temp < maxObj?.temp ? currentObj : maxObj;
                          },
                        );
                        setLowestTempObj([minTemp]);
                        // 获取最高/最低电压
                        const maxVol = moduleRes.data.reduce(
                          (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
                            return currentObj?.voltage > maxObj?.voltage ? currentObj : maxObj;
                          },
                        );
                        setHighestVolObj([maxVol]);
                        const minVol = moduleRes.data.reduce(
                          (maxObj: API.BmuRealTimeData, currentObj: API.BmuRealTimeData) => {
                            return currentObj?.voltage < maxObj?.voltage ? currentObj : maxObj;
                          },
                        );
                        setLowestVolObj([minVol]);
                        setModuleArray(moduleRes.data);
                        setModuleLoading(false);
                        handleSelectModule(module);
                      })
                      .catch(() => {
                        setModuleLoading(false);
                      });
                  } else {
                    setStackName('');
                    setBreakNum(0);
                    setHighestTempObj([]);
                    setLowestTempObj([]);
                    setHighestVolObj([]);
                    setLowestVolObj([]);
                    setModuleArray([]);
                    setUnitArray([]);
                    setModuleFaultCount('');
                    setModuleName('');
                    setModuleLoading(false);
                  }
                } else {
                  setStackName('');
                  setBreakNum(0);
                  setStackArray([]);
                  stackArrayRef.current = [];
                  setModuleName('');
                  setModuleFaultCount('');
                  setModuleArray([]);
                  setUnitArray([]);
                  setHighestTempObj([]);
                  setLowestTempObj([]);
                  setHighestVolObj([]);
                  setLowestVolObj([]);
                }
              });
            });
          }
        }
      });
    }, 60000);
  };
  useEffect(() => {
    setBoxLoading(true);
    setClusterLoading(true);
    batteryControllerGetBatteryBoxs({ stationId: initialState?.stationId })
      .then((res) => {
        setBoxLoading(false);
        setClusterLoading(false);
        if (res.data && res.data.length > 0) {
          setBoxArray(res.data);
          handleSelectBox(res.data[0]);
          setTimeEvent();
          batteryControllerGetBmsRealTimeData({
            stationId: initialState?.stationId,
            boxCode: res.data[0].code,
          }).then((clusterRes) => {
            if (clusterRes.data) {
              setStackArray(clusterRes?.data);
              stackArrayRef.current = clusterRes?.data;
              setSelectedStack(clusterRes?.data[0]?.code);
              selectedStackRef.current = clusterRes?.data[0]?.code;
              handleSelectStack(
                clusterRes?.data[0]?.clusterList ? clusterRes?.data[0]?.clusterList[0] : [],
              );
              setClusterArray(clusterRes?.data[0]?.clusterList);
              clusterArrayRef.current = clusterRes?.data[0]?.clusterList;
            }
          });
        } else {
          setBoxArray([]);
          setStackArray([]);
          stackArrayRef.current = [];
        }
      })
      .catch(() => {
        setBoxLoading(false);
        setClusterLoading(false);
      });
    return () => {
      clearInterval(realTimeInterval);
    };
  }, []);
  const location = useLocation();

  useEffect(() => {
    const hash = location.hash;
    if (hash) {
      setTimeout(() => {
        const element = document.querySelector(hash);
        if (element) {
          element.scrollIntoView({ behavior: 'smooth' });
        } else {
        }
      }, 100); // 延迟以确保页面内容加载完毕
    }
  }, [location]);

  return (
    <div>
      <Flex vertical={true} gap={'middle'} style={{ width: 'auto', height: '18%' }}>
        <Card style={{ border: 'none' }} className={Styles.realTime}>
          <Spin spinning={boxLoading}>
            <Flex className={Styles.BoxContent}>
              {boxArray?.length > 0 ? (
                (boxArray || []).map((item: API.BatteryBox) => (
                  <div
                    onClick={() => {
                      handleSelectBox(item);
                    }}
                    key={item.code}
                    className={cls([
                      {
                        [Styles.BoxBase]: true,
                        [Styles.BoxBaseSelected]: selectedBox === item.code,
                        [Styles.Base]: item.faultCount === 0,
                        [Styles.Small]: item?.faultCount >= 1 && item?.faultCount < 10,
                        [Styles.Middle]: item.faultCount >= 10 && item.faultCount < 20,
                        [Styles.Large]: item.faultCount > 20,
                      },
                    ])}
                  >
                    <div className={Styles.BoxContentTitle}>{item.name}</div>
                    {/* <div className={Styles.BoxContentBreak}>
                      故障数 &nbsp;
                      // {item.faultCount}
                    </div> */}
                    <div
                      className={cls([
                        {
                          [Styles.BoxContentStatus]: true,
                        },
                      ])}
                      style={{
                        backgroundColor: boxColorMap.get(item.workState),
                      }}
                    >
                      {item.online ? boxStatusMap.get(item.workState) : '离线'}
                    </div>
                  </div>
                ))
              ) : (
                <Empty />
              )}
            </Flex>
          </Spin>
        </Card>
        <Card
          id="batteryDetails"
          title={
            <div>
              <Flex justify={'space-between'}>
                <div>电池箱监测详情</div>
                <div>
                  <Select
                    value={selectedBox}
                    placeholder={'电池箱'}
                    options={boxArray}
                    fieldNames={{
                      value: 'code',
                      label: 'name',
                    }}
                    onSelect={(e, value) => {
                      handleSelectBox(value);
                    }}
                  ></Select>
                </div>
              </Flex>
            </div>
          }
          hasHeaderBorder={true}
        >
          <Spin spinning={boxLoading}>
            <Flex style={{ width: '100%' }}>
              <Card
                style={{ flex: 1, boxShadow: 'none' }}
                title={
                  <div>
                    <span key="title" className={Styles.CardTitle}>
                      电池{boxName}监测情况
                    </span>
                    <span key={'block'}>&nbsp;</span>
                    <span
                      key="status"
                      className={Styles.StackContentStatus}
                      style={{
                        fontSize: '14px',
                      }}
                    >
                      <span style={{ color: boxColor }}>{boxState}</span>
                    </span>
                  </div>
                }
                bordered={false}
              >
                <div className={Styles.BoxView}>
                  <Flex vertical={true} justify={'space-between'} style={{ height: '100%' }}>
                    <Flex justify={'space-around'}>
                      <Flex gap={'middle'}>
                        <div>
                          <img src={SOCIcon} alt={''} />
                        </div>
                        <Flex vertical={true} className={Styles.BoxTitleBox}>
                          <div className={Styles.BoxTitle}>SOC(%)</div>
                          <div className={Styles.BoxText}>{boxInfo?.soc}</div>
                        </Flex>
                      </Flex>
                      <Flex gap={'middle'} style={{ opacity: '0' }}>
                        <div>
                          <img src={FailureIcon} alt={''} />
                        </div>
                        <Flex vertical={true} className={Styles.BoxTitleBox}>
                          <div className={Styles.BoxTitle}>故障数量(条)</div>
                          <div className={Styles.BoxText}>{boxInfo?.faultCount}</div>
                        </Flex>
                      </Flex>
                    </Flex>
                    <Flex justify={'space-around'}>
                      <Flex gap={'middle'}>
                        <div>
                          <img src={DischargeIcon} alt={''} />
                        </div>
                        <Flex vertical={true} className={Styles.BoxTitleBox}>
                          <div className={Styles.BoxTitle}>
                            可放电量({boxInfo?.dischargeCapacityUnit})
                          </div>
                          <div className={Styles.BoxText}>{boxInfo?.dischargeCapacity}</div>
                        </Flex>
                      </Flex>
                      <Flex gap={'middle'}>
                        <div>
                          <img src={ChargeIcon} alt={''} />
                        </div>
                        <Flex vertical={true} className={Styles.BoxTitleBox}>
                          <div className={Styles.BoxTitle}>
                            可充电量({boxInfo?.chargeCapacityUnit})
                          </div>
                          <div className={Styles.BoxText}>{boxInfo?.chargeCapacity}</div>
                        </Flex>
                      </Flex>
                    </Flex>
                  </Flex>
                </div>
              </Card>
              <Card title="当日放电量" bordered={false} style={{ flex: 1, boxShadow: 'none' }}>
                <EchartsComponent option={dischargeOptions} height={'18rem'} />
              </Card>
            </Flex>
          </Spin>
        </Card>
        <Card
          id="batteryCluster"
          hasHeaderBorder={true}
          title={'每箱簇监控'}
          extra={
            <Space>
              <Select
                placeholder={'电池箱'}
                options={boxArray}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                value={selectedBox}
                onSelect={(e, value) => {
                  handleSelectBox(value);
                }}
              ></Select>
              <Select
                value={boxInfoType}
                onChange={(value: string) => {
                  setBoxInfoType(value);
                  if (value === 'temp') {
                    setBoxInfoArray(switchTempArray);
                    setBoxArrayType('realtimeTemp');
                  } else {
                    setBoxInfoArray(switchVolArray);
                    setBoxArrayType('realtimeVol');
                  }
                }}
                placeholder={'温度示意图'}
                options={switchInfoArray}
              ></Select>
              <Select
                style={{ width: 180 }}
                value={boxArrayType}
                onChange={(value: string) => {
                  setBoxArrayType(value);
                }}
                placeholder={'实时温度图'}
                options={boxInfoArray}
              ></Select>
            </Space>
          }
        >
          <Spin spinning={clusterLoading}>
            <Flex justify={'space-between'}>
              <div className={Styles.StackTitle}>{boxName}</div>
              <Space className={Styles.ColorMap}>
                温度 <ColorMap />
              </Space>
            </Flex>
            {stackArray?.length > 0 ? (
              stackArray.map((item: API.BmsRealTimeData) => {
                return (
                  <Flex align="center" key={item.code} style={{ marginBottom: '20px' }}>
                    <div className={Styles.StackContent}>
                      <div>
                        <span className={Styles.StackContentTitle}>{item.name}</span>
                        <span
                          className={Styles.StackContentStatus}
                          style={{
                            backgroundColor: item.communicationState === 1 ? '#1a6cfe' : '#FF5353',
                          }}
                        >
                          通讯{item.communicationState === 1 ? '正常' : '异常'}/
                          {boxStatusMap.get(item.workState)}
                        </span>
                      </div>
                      <div className={Styles.StackContentText}>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>充放电状态：</div>
                          <div className={Styles.StackContentTextValue}>
                            {boxStatusMap.get(item.workState)}
                          </div>
                        </Flex>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>等效循环次数：</div>
                          <div className={Styles.StackContentTextValue}>
                            {item.cycleTimes !== 0 ? item.cycleTimes || '-' : 0}
                          </div>
                        </Flex>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>SOC(%)：</div>
                          <div className={Styles.StackContentTextValue}>
                            {item.soc?.toFixed(2) || '-'}
                          </div>
                        </Flex>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>
                            运行功率({item.powerUnit})：
                          </div>
                          <div className={Styles.StackContentTextValue}>
                            {item.power?.toFixed(2) || '-'}
                          </div>
                        </Flex>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>在线率(%)：</div>
                          <div className={Styles.StackContentTextValue}>
                            {item.onlineRate?.toFixed(2) || '-'}
                          </div>
                        </Flex>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>簇温度(℃)Max/Min：</div>
                          <div className={Styles.StackContentTextValue}>
                            {item?.tmax?.toFixed(2) || '-'}/{item?.tmin?.toFixed(2) || '-'}
                          </div>
                        </Flex>
                        <Flex>
                          <div className={Styles.StackContentTextLabel}>簇电压(V)Max/Min：</div>
                          <div className={Styles.StackContentTextValue}>
                            {item.vmax?.toFixed(2) || '-'}/{item.vmin?.toFixed(2) || '-'}
                          </div>
                        </Flex>
                      </div>
                    </div>
                    <Flex className={Styles.StackList}>
                      {(item?.clusterList || []).map((item: API.ClusterRealTimeData) => (
                        <div
                          style={{
                            zIndex: 3,
                            position: 'relative',
                          }}
                          onClick={() => {
                            handleSelectStack(item);
                          }}
                          key={item.code}
                        >
                          <Flex
                            vertical={true}
                            className={cls([
                              {
                                [Styles.StackBaseBox]: true,
                                [Styles.StackBaseBoxSelected]: selectedCluster === item.code,
                                [Styles.StackBase]: item.temp >= 0 && item.temp < 30,
                                [Styles.StackSmall]: item.temp >= 30 && item.temp < 60,
                                [Styles.StackMiddle]: item.temp >= 60 && item.temp < 80,
                                [Styles.StackHigh]: item.temp >= 80,
                              },
                            ])}
                          >
                            <div className={Styles.StackBaseText}>
                              <div>{'簇' + item.name?.split('簇')[1]}</div>
                              {boxArrayType === 'realtimeTemp' ? (
                                <div>温度：{item.temp?.toFixed(2) || '-'}(℃)</div>
                              ) : boxArrayType === 'realtimeTempGap' ? (
                                <div>温差：{item.tempDiff?.toFixed(2) || '-'}(℃)</div>
                              ) : boxArrayType === 'realtimeVol' ? (
                                <div>电压：{item.voltage?.toFixed(2) || '-'}(V)</div>
                              ) : (
                                <div>压差：{item.voltageDiff?.toFixed(2) || '-'}(V)</div>
                              )}
                              <div style={{ display: 'none' }}>故障：{item.faultCount}</div>
                              {item.faultList && item.faultList.length > 2 ? (
                                <div>
                                  <div>故障1：{item.faultList[0]}</div>
                                  <div>故障2：{item.faultList[1]}</div>
                                </div>
                              ) : (
                                item?.faultList?.map((lItem, index) => {
                                  return (
                                    <div key={index}>
                                      故障{index + 1}：{lItem}
                                    </div>
                                  );
                                })
                              )}
                            </div>
                          </Flex>
                          <div
                            className={Styles.StackBaseStatus}
                            style={{
                              backgroundColor: boxColorMap.get(item.workState),
                            }}
                          >
                            {boxStatusMap.get(item.workState)}
                          </div>
                          <div className={Styles.StackBaseAm}>
                            电流（A）{item.current?.toFixed(2) || '-'}
                          </div>
                        </div>
                      ))}
                    </Flex>
                  </Flex>
                );
              })
            ) : (
              <Empty></Empty>
            )}
          </Spin>
        </Card>
        <Card
          hasHeaderBorder={true}
          title={
            <span>
              每簇模组监控 &nbsp;
              <span className={Styles.CardTitle}>簇名称:{stackName}</span>
              &nbsp;
              <span className={Styles.CardTitle} style={{ display: 'none' }}>
                故障:
                {breakNum}条
              </span>
            </span>
          }
          extra={
            <Space>
              <Select
                placeholder={'电池箱'}
                options={boxArray}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                value={selectedBox}
                onSelect={(e, value) => {
                  handleSelectBox(value);
                }}
              ></Select>
              <Select
                // value={selectedStack}
                value={selectedStackRef?.current}
                placeholder={'电池堆'}
                options={stackArray}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                onSelect={(e, value) => {
                  handleSelectedStack(value);
                }}
              ></Select>
              <Select
                value={selectedCluster}
                placeholder={'电池簇'}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                options={clusterArrayRef.current}
                // options={clusterArray}
                onSelect={(e, value) => {
                  handleSelectStack(value);
                }}
              ></Select>
              <Select
                value={clusterInfoType}
                onChange={(value: string) => {
                  setClusterInfoType(value);
                  if (value === 'temp') {
                    setClusterInfoArray(switchTempArray);
                    setClusterArrayType('realtimeTemp');
                  } else {
                    setClusterInfoArray(switchVolArray);
                    setClusterArrayType('realtimeVol');
                  }
                }}
                placeholder={'温度示意图'}
                options={switchInfoArray}
              ></Select>
              <Select
                style={{ width: 180 }}
                value={clusterArrayType}
                options={clusterInfoArray}
                placeholder={'实时温度图'}
                onChange={(value: string) => {
                  setClusterArrayType(value);
                }}
              ></Select>
            </Space>
          }
        >
          <Spin spinning={moduleLoading}>
            <Flex gap={'large'} style={{ height: '28rem' }}>
              {/*左侧温度表*/}
              <Flex vertical={true} className={Styles.ClusterContentLeft}>
                {clusterInfoType === 'temp' ? (
                  <div style={{ flex: 1 }}>
                    <div className={Styles.ClusterTitle}>实时温度(℃)Max/Min</div>
                    {/*最高温度*/}
                    <Table
                      style={{ maxHeight: 120 }}
                      search={false}
                      rowKey={'code'}
                      dataSource={highestTempObj}
                      scroll={{ x: 'max-content' }}
                      columns={highestTempTableColumns}
                      pagination={false}
                      size="small"
                    ></Table>
                    {/*最低温度*/}
                    <Table
                      rowKey={'code'}
                      style={{ maxHeight: 120 }}
                      dataSource={lowestTempObj}
                      scroll={{ x: 'max-content' }}
                      columns={lowestTempTableColumns}
                      pagination={false}
                      size="small"
                    ></Table>
                  </div>
                ) : (
                  <div style={{ flex: 1 }}>
                    <div className={Styles.ClusterTitle}>实时电压(V)Max/Min</div>
                    <Table
                      rowKey={'code'}
                      dataSource={highestVolObj}
                      size="small"
                      style={{ maxHeight: 120 }}
                      scroll={{ x: 'max-content' }}
                      columns={highestVolTableColumns}
                      pagination={false}
                    ></Table>
                    <Table
                      rowKey={'code'}
                      size="small"
                      dataSource={lowestVolObj}
                      style={{ maxHeight: 120 }}
                      scroll={{ x: 'max-content' }}
                      columns={lowestVolTableColumns}
                      pagination={false}
                    ></Table>
                  </div>
                )}
              </Flex>
              {/*  右侧模组列表*/}
              <div style={{ width: '79%', textAlign: 'right' }}>
                <Space>
                  {/*<span>←风流向</span>*/}
                  温度
                  <ColorMap />
                </Space>
                <div className={Styles.ClusterContent}>
                  {moduleArray?.length > 0 ? (
                    moduleArray.map((item: API.BmuRealTimeData) => {
                      return (
                        <div
                          onClick={() => {
                            handleSelectModule(item);
                          }}
                          key={item.code}
                          className={cls([
                            {
                              [Styles.ClusterBaseBox]: true,
                              [Styles.ClusterBaseBoxSelected]: item.code === selectedModule,
                              [Styles.ClusterBase]: item.temp >= 0 && item.temp < 30,
                              [Styles.ClusterBaseSmall]: item.temp >= 30 && item.temp < 60,
                              [Styles.ClusterBaseMiddle]: item.temp >= 60 && item.temp < 80,
                              [Styles.ClusterBaseHigh]: item.temp >= 80,
                            },
                          ])}
                        >
                          <Flex vertical={true} className={Styles.ClusterText}>
                            <div>{'模组' + item.name?.split('模组')[1]}</div>
                            {clusterArrayType === 'realtimeTemp' ? (
                              <div>温度：{item.temp?.toFixed(2) || '-'}(℃)</div>
                            ) : clusterArrayType === 'realtimeTempGap' ? (
                              <div>温差：{item.tempDiff?.toFixed(2) || '-'}(℃)</div>
                            ) : clusterArrayType === 'realtimeVol' ? (
                              <div>电压：{item.voltage?.toFixed(2) || '-'}(V)</div>
                            ) : (
                              <div>压差：{item.voltageDiff?.toFixed(2) || '-'}(V)</div>
                            )}
                            <div style={{ display: 'none' }}>故障：{item.faultCount}</div>
                            {item.faultList && item.faultList.length > 2 ? (
                              <div style={{ display: 'none' }}>
                                <div>故障1：{item.faultList[0]}</div>
                                <div>故障2：{item.faultList[1]}</div>
                              </div>
                            ) : (
                              item?.faultList?.map((lItem, index) => {
                                return (
                                  <div key={index} style={{ display: 'none' }}>
                                    故障{index + 1}：{lItem}
                                  </div>
                                );
                              })
                            )}
                          </Flex>
                        </div>
                      );
                    })
                  ) : (
                    <Empty></Empty>
                  )}
                </div>
              </div>
            </Flex>
          </Spin>
        </Card>
        <Card
          hasHeaderBorder={true}
          title={
            <span>
              每模组单元监控&nbsp;
              <span className={Styles.CardTitle}>模组名称：{moduleName}</span>&nbsp;
              <span className={Styles.CardTitle} style={{ display: 'none' }}>
                故障：{moduleFaultCount}条
              </span>
            </span>
          }
          extra={
            <Space>
              <Select
                placeholder={'电池箱'}
                options={boxArray}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                value={selectedBox}
                onSelect={(e, value) => {
                  handleSelectBox(value);
                }}
              ></Select>
              <Select
                value={selectedStackRef?.current}
                placeholder={'电池堆'}
                options={stackArray}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                onSelect={(e, value) => {
                  handleSelectedStack(value);
                }}
              ></Select>
              <Select
                value={selectedCluster}
                placeholder={'电池簇'}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                options={clusterArrayRef?.current || []}
                // options={clusterArray}
                onSelect={(e, value) => {
                  handleSelectStack(value);
                }}
              ></Select>
              <Select
                value={selectedModule}
                fieldNames={{
                  value: 'code',
                  label: 'name',
                }}
                placeholder={'电池模组'}
                options={moduleArray}
                onSelect={(e, value) => {
                  handleSelectModule(value);
                }}
              ></Select>
              <Select
                value={unitInfoType}
                onChange={(value: string) => {
                  setUnitInfoType(value);
                  setUnitArray(
                    unitArrayInit.slice(
                      0,
                      value === 'temp' ? unitCount.tempCount : unitCount.voltCount,
                    ),
                  );
                }}
                placeholder={'温度示意图'}
                options={switchInfoArray}
              ></Select>
            </Space>
          }
        >
          <Space className={Styles.ColorMap} style={{ justifyContent: 'right' }}>
            温度
            <ColorMap />
          </Space>
          <Spin spinning={unitLoading}>
            <div className={Styles.Unit}>
              <Flex className={Styles.UnitContent}>
                {unitArray?.length > 0 ? (
                  unitArray.map((item: API.BmuUnitRealTimeData) => {
                    return (
                      <div
                        key={item.unitId}
                        className={cls([
                          {
                            [Styles.UnitContentBox]: true,
                            [Styles.UnitNormal]: Number(item.temp) >= 0 && Number(item.temp) < 30,
                            [Styles.UnitSmall]: Number(item.temp) >= 30 && Number(item.temp) < 60,
                            [Styles.UnitMiddle]: Number(item.temp) >= 60 && Number(item.temp) < 80,
                            [Styles.UnitHigh]: Number(item.temp) >= 80,
                          },
                        ])}
                      >
                        <div className={Styles.UnitText}>
                          <div>{item.name}</div>
                          <div style={{ wordBreak: 'break-all', textWrap: 'wrap' }}>
                            ID：{item.unitId}
                          </div>
                          {unitInfoType === 'temp' ? (
                            <div className={Styles.UnitTempVolText}>
                              温度：{item.temp || '-'}(℃)
                            </div>
                          ) : (
                            <div className={Styles.UnitTempVolText}>
                              电压：{item.voltage || '-'}(V)
                            </div>
                          )}
                          {item.faultList && item.faultList.length > 4 ? (
                            <div>
                              <Flex justify={'space-between'}>
                                <div style={{ display: 'none' }}>故障：{item.faultList[0]}</div>
                                <div>故障：{item.faultList[1]}</div>
                              </Flex>
                              <Flex justify={'space-between'}>
                                <div style={{ display: 'none' }}>故障：{item.faultList[2]}</div>
                                <div style={{ display: 'none' }}>故障：{item.faultList[3]}</div>
                              </Flex>
                            </div>
                          ) : (
                            item?.faultList?.map((lItem, index) => {
                              return (
                                <div key={index} style={{ display: 'none' }}>
                                  故障{index + 1}：{lItem}
                                </div>
                              );
                            })
                          )}
                        </div>
                        {item.faultCount > 0 && (
                          <div className={Styles.UnitBreak} style={{ display: 'none' }}>
                            故障{item.faultCount}
                          </div>
                        )}
                      </div>
                    );
                  })
                ) : (
                  <Empty></Empty>
                )}
              </Flex>
            </div>
          </Spin>
        </Card>
      </Flex>
    </div>
  );
};

export default RealtimeMonitor;
